import 'package:cash_drawer/ui/system_page.dart';
import 'package:cash_drawer/ui/table_page.dart';
import 'package:cash_drawer/utils/utils.dart';
import 'package:flutter/material.dart';



class MainPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _MainPage();
  }
}

class _MainPage extends State<MainPage>
    with AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController();
  int _selectedIndex = 0; // 当前选中的索引

  final bottomBarTitles = ["桌台", "更多"];

  var pages = <Widget>[
    TablePage(),
    SystemScreen()
  ];


  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        body: PageView.builder(
          itemBuilder: (context, index) => pages[index],
          itemCount: pages.length,
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: buildImage(0, "ic_home"), //Icon(Icons.home),
              title: Text(bottomBarTitles[0]),
            ),
            BottomNavigationBarItem(
              icon: buildImage(1, "ic_system"), //Icon(Icons.assignment),
              title: Text(bottomBarTitles[1]),
            ),
          ],
          type: BottomNavigationBarType.fixed, // 设置显示模式
          currentIndex: _selectedIndex, // 当前选中项的索引
          onTap: _onItemTapped, // 选择的处理事件
        ),
      ),
    );
  }

  void _onItemTapped(int index) {
    _pageController.jumpToPage(index);
  }

  Widget buildImage(index, iconPath) {
    return Image.asset(
      Utils.getImgPath(iconPath),
      width: 22,
      height: 22,
      color: _selectedIndex == index
          ? Theme.of(context).primaryColor
          : Colors.grey[600],
    );
  }

  Future<bool> _onWillPop() {
    return showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('提示'),
        content: new Text('确定退出应用吗？'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text('再看一会', style: TextStyle(color: Colors.cyan)),
          ),
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: new Text('退出', style: TextStyle(color: Colors.cyan)),
          ),
        ],
      ),
    ) ??
        false;
  }

}